export const useScan = () => {
  let main;
  let receiver;
  let filter;
  let _codeQueryTag = false;
  
  const initScan = () => {
    console.log('initScan')
    let type = uni.getSystemInfoSync().platform
    if (type === 'android') {
      main = plus.android.runtimeMainActivity(); //获取activity
      const IntentFilter = plus.android.importClass('android.content.IntentFilter');
      filter = new IntentFilter();
      filter.addAction('com.android.server.scannerservice.broadcast'); // 换你的广播动作
      receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
        onReceive: function(context, intent) {
          plus.android.importClass(intent);
          const code = intent.getStringExtra('scannerdata'); // 换你的广播标签
          queryCode(code);
        }
      });
      startScan();
    }
    
  }
  
  const startScan = () => {
    main.registerReceiver(receiver, filter);
  }
  
  const stopScan = () => {
    main.unregisterReceiver(receiver);
  }
  
  const queryCode = (code) => {
    //防重复
    if (_codeQueryTag) return false;
    _codeQueryTag = true;
    setTimeout(function() {
      _codeQueryTag = false;
    }, 150);
    uni.$emit('scancode', {
      code
    });
  }
  
  initScan()
}